const axios = require('axios');
const puppeteer = require('puppeteer-core');

const exec = require('child_process').exec;
const kill = require('tree-kill');

/* 关闭浏览器 */
const closeBrowser = async () => {
  let cmd = process.platform === 'win32' ? 'tasklist' : 'ps aux'
  const closeB = new Promise((resolve, reject) => {
    exec(cmd, (err, stdout, stderr) => {
      if (err) {
        reject(err)
      }
      let arr = []
      stdout.split('\n').map(item => {
        arr.push({ name: item.trim().split(/\s+/)[0], pid: item.trim().split(/\s+/)[1] })
      })

      // ['QQBrowser.exe', 'chrome.exe', 'iexplore.exe', 'firefox.exe', 'sogouexplorer.exe',
      //   'opera.exe', '360SE.exe', 'Maxthon.exe', 'Netscape.exe', '360chrome.exe', 'msedge.exe']
      /* 要kill的浏览器类型 */
      let data = ['chrome.exe']
      let killArr = []
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < data.length; j++) {
          if (arr[i].name == data[j]) {
            killArr.push(arr[i].pid)
          }
        }
      }
      for (let i = 0; i < killArr.length; i++) {
        kill(killArr[i])
      }
      resolve()
    })
  });
  return closeB
}

// 打开新浏览器
const openDefaultBrowser = async (url) => {
  const openB = new Promise((resolve, reject) => {
    switch (process.platform) {
      case "darwin":
        exec(`open ${url}`, (error, stdout, stderr) => {
          if (error) {
            reject(error)
          }
        }).on(`exit`, (code) => {
          console.log(`darwin子进程已退出, 退出码 ` + code);
          resolve()
        })
        break;
      case "win32":
        exec(`start ${url}`, (error, stdout, stderr) => {
          if (error) {
            reject(error)
          }
        }).on('exit', (code) => {
          console.log('win32子进程已退出, 退出码 ' + code);
          resolve()
        });
        break;
      default:
        exec(`xdg-open ${url}`, (error, stdout, stderr) => {
          if (error) {
            reject(error)
          }
        }).on('exit', (code) => {
          console.log('xdg-open子进程已退出, 退出码 ' + code);
          resolve()
        });
    }
  });
  return openB
}

(async () => {
  /* 文档上要求使用try，catch包裹async */
  try {
    /* 先关闭chrome */
    await closeBrowser()
    /* 带参数打开浏览器 */
    await openDefaultBrowser(`C:\\Progra~1\\Google\\Chrome\\Application\\chrome.exe --remote-debugging-port=9222`);
    /* 延迟一秒执行，打开浏览器需要时间 */
    setTimeout(async () => {
      /* 获取浏览器信息，与打开的浏览器建立连接 */
      let wsKey = await axios.get('http://localhost:9222/json/version');
      let browser = await puppeteer.connect({
        browserWSEndpoint: wsKey.data.webSocketDebuggerUrl,
        defaultViewport: null
      });
      let page = await browser.newPage()
      await Promise.all([
        // 等待页面加载完毕
        page.goto('https://taobao.com'),
        page.waitForNavigation(),
      ])
    
      // 搜索关键字
      var keyName = '小米手机';
      // 等待输入框加载完毕
      await page.$('#q');
      // 输入关键字
      await page.type('input[id=q]', keyName, { delay: 1000 });
      // 点击搜索按钮
      await page.click('.btn-search');
      // 等待2秒后进入采集方法
      await page.waitFor(2000);
      await page.close()
      await browser.disconnect()
      
    }, 1000);
  } catch (err) {
    await closeBrowser()
  }
})()